package leetcode.editor.cn.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Java 数组与List的互相转换
 */
public class ArrToListUtil {
    public static void main(String[] args) {
        //stream 比较通用，toArray() 对基本类型如 int 不适用，实在忘了就老老实实写循环复制一遍
        /**
         * 一维相关
         */
        // int[] 转 List<Integer>
        int[] arr = {1, 2, 3, 4, 5};
        List<Integer> collect = Arrays.stream(arr).boxed().collect(Collectors.toList());

        IntStream stream = Arrays.stream(arr);
        Stream<Integer> boxed = stream.boxed();
        List<Integer> collect1 = boxed.collect(Collectors.toList());

        Stream<Integer> stream1 = collect.stream();


        // List<Integer> 的数据生成一个新的 List
        ArrayList<Integer> integers1 = new ArrayList<>(collect);

        // List<Integer> 转 int[]
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        int[] arr1 = integerList.stream().mapToInt(x -> x).toArray();

        /**
         * 二维相关
         */

        // int[][] 转 List<List<Integer>>
        int[][] arr2d = {{1, 10}, {2, 20}, {3, 30}};
        List<List<Integer>> arr2dList = new ArrayList<>();
        for (int[] array : arr2d) {
            arr2dList.add(Arrays.stream(array).boxed().collect(Collectors.toList()));
        }

        // int[][] 转 List<int[]>
        List<int[]> list1 = Arrays.stream(arr2d).collect(Collectors.toList());

        // List<int[]> 转 int[][]
        List<int[]> list = new ArrayList<>(Arrays.asList(new int[]{1, 10}, new int[]{2, 20}, new int[]{3, 30}));
        int[][] arr2d1  = list.toArray(new int[0][]);  // new int[0][]起到模板作用

        // List<List<Integer>> 转 int[][]
        int[][] array = list.stream()
                .map(Arrays::stream)
                .map(IntStream::toArray)
                .toArray(int[][]::new);
        System.out.println();


    }
}
